# -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, with_statement
import json
import uuid

from kafka import KafkaConsumer, KafkaProducer
from kafka.errors import KafkaError

from .message_config import MessageConfig
from .registered import Registered


class Message(object):
    '''
    kafka消息订阅和生产，基于kafka-python==1.4.6
    有三个方法receive_message、register、producer_message
    其中register为装饰器，注册消息的handler
    * 'bootstrap_servers' kafka服务器,str或list (如：'115.29.76.68:9092' or ['115.29.76.68:9092'])
    '''

    def __init__(self, bootstrap_servers):
        self.registered = Registered()
        self.bootstrap_servers = bootstrap_servers

    def receive_message(self, topic, group_id=None, auto_offset_reset='latest'):
        '''
        * 'topic' 订阅的tpic,类型是list,如['cw-get', 'all-msg']
        * 'group_id' 消费者属于的组名，同一个组中多个消费者，一条消息只被消费一次
        * 'auto_offset_reset' latest从最后开始订阅，earliest从最早订阅
        '''
        consumer = KafkaConsumer(
            *topic,
            group_id=group_id,
            auto_offset_reset=auto_offset_reset,
            bootstrap_servers=self.bootstrap_servers
        )
        try:
            for message in consumer:
                config = self.registered.get_config(message)
                if config:
                    try:
                        config.func(message)
                    except Exception as e:
                        print(e)
                else:
                    pass
        except KafkaError as e:
            print(e)

    def register(self, method='GET', app='org', uri_pattern=' '):
        '''
        装饰器
        * 'method' 匹配uri方法
        * 'app' 业务端org、crm等
        * 'uri_pattern' uri匹配的正则表达式
            如 (https|http)://(.*)/entities/([a-f\d]{8}([a-f\d]{4}){3}[a-f\d]{12}?)
        '''
        def do_register(func):
            msg_confg = MessageConfig(
                method=method,
                func=func,
                app=app,
                uri_pattern=uri_pattern
            )
            self.registered.append(msg_confg)
            return func
        return do_register

    def producer_message(self, value, topic, key=None, ):
        '''
        * 'topic' str类型
        * 'value' dict类型,有具体的要求
        * 'key' uuid.uuid4().hex.encode() 可不指定


        '''
        producer = KafkaProducer(bootstrap_servers=self.bootstrap_servers,
                                 value_serializer=lambda x: json.dumps(x).encode(encoding='ascii'))
        if key is None:
            key = uuid.uuid4().hex.encode()
        send = producer.send(topic, key=key, value=value, partition=0)
        try:
            result = send.get(timeout=10)
            return result
        except KafkaError:
            return False
